package edu.hziee.controllers;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import edu.hziee.dao.UserDao;
import edu.hziee.model.User;

@Controller
@RequestMapping("/login")
public class LoginController {

	@Autowired
	UserDao userDao;
	
	@RequestMapping(method=RequestMethod.GET)
	public String login(){
		return "login/login";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public ModelAndView login(@RequestParam String userName, 
			@RequestParam String password, HttpSession session){
		ModelAndView mav = new ModelAndView();
		User user = userDao.selectUserByName(userName);
		
		if( user==null || !password.equals(user.getPassword())){
			mav.addObject("errorMsg", "用户名或者密码错误！");
			mav.setViewName("login/login");
		}
		else{
			session.setAttribute("user", user);
			mav.setViewName("redirect:/");
		}
		return mav;
	}
	
	@RequestMapping(value="/logout", method=RequestMethod.GET)
	public String logout(){
		return "redirect:/home";
	}
}
